{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def find(data, i):\n",
    "    if i != data[i]:\n",
    "        data[i] = find(data, data[i])\n",
    "    return data[i]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def union(data, i, j):\n",
    "    pi, pj = find(data, i), find(data, j)\n",
    "    if pi != pj:\n",
    "        data[pi] = pj"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def connected(data, i, j):\n",
    "    return find(data, i) == find(data, j)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "item 0 -> component 9\n",
      "item 1 -> component 9\n",
      "item 2 -> component 9\n",
      "item 3 -> component 3\n",
      "item 4 -> component 9\n",
      "item 5 -> component 9\n",
      "item 6 -> component 9\n",
      "item 7 -> component 7\n",
      "item 8 -> component 8\n",
      "item 9 -> component 9\n"
     ]
    }
   ],
   "source": [
    "n = 10\n",
    "data = [i for i in range(n)]\n",
    "connections = [(0, 1), (1, 2), (0, 9), (5, 6), (6, 4), (5, 9)]\n",
    "\n",
    "# union\n",
    "for i, j in connections:\n",
    "    union(data, i, j)\n",
    "\n",
    "# find\n",
    "for i in range(n):\n",
    "    print('item', i, '-> component', find(data, i))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
